﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using GRWL.BZSC.UI.CustomCtrl;
using System.Collections;
using DgvFilterPopup;

namespace GRWL.BZSC.UI
{
    public partial class FindMaterialFrm : BaseFrm
    {
        /// <summary>
        /// 单选时当前选择项
        /// </summary>
        public QMaterial SelectorItem { get; set; }

        /// <summary>
        /// 运许多选
        /// </summary>
        public bool MutiSelect { get; set; }

        /// <summary>
        /// 搜查库存可空的物料
        /// </summary>
        public bool StockNullable { get; set; }

        /// <summary>
        /// 搜查物料是否为采购件
        /// </summary>
        public bool? IsPurchase { get; set; }

        /// <summary>
        /// 临时变量
        /// </summary>
        QMaterial[] DataAry { get; set; }

        /// <summary>
        /// 过滤器
        /// </summary>
        DgvFilterManager _DgvFm = null;

        public GRWL.BZSC.Common.EnumCommon.OptionType CurrentType { get; set; }

        public FindMaterialFrm()
        {
            InitializeComponent();
            this.BaseDataProxy = new GRWL.BZSC.UI.BaseDataSvc.BaseDataClient();
        }

        private void MaterialFrm_Load(object sender, EventArgs e)
        {
            this.BaseDataProxy.Open();
            this._DgvFm = new DgvFilterManager();
            this._DgvFm.ColumnFilterAdding += new ColumnFilterEventHandler(initDgvFilter);
            initDgvColumns();
            this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.物料分类;
            if (!this.MutiSelect)
            {
                this.btnInsert.Visible = false;
                this.btnClear.Visible = false;
                this.btnSelectAll.Visible = false;
            }

            bindTree(this.uTreeView1);
        }

        private void bindTree(UserCtrl.UTreeView tv)
        {
            TB_Options[] options = this.BaseDataProxy.GetOptionTree(this.CurrentType.ToString());
            Common.BindOptionTree(tv, options, this.CurrentType.ToString());
            if (this.CurrentType == GRWL.BZSC.Common.EnumCommon.OptionType.仓库分类)
            {
                TB_Depot[] ary = this.BaseDataProxy.FindDepots(string.Empty, string.Empty, null);
                if (ary != null)
                    loadDepot(ary);
            }
        }

        private void loadDepot(TB_Depot[] ary)
        {
            foreach (TreeNode node in this.uTreeView2.Nodes[0].Nodes)
            {
                if (node.ImageIndex == 2)
                {
                    int category = Convert.ToInt32(node.Name);
                    var query = from q in ary where q.type == category select q;
                    if (query != null)
                    {
                        foreach (TB_Depot d in query)
                        {
                            TreeNode child = new TreeNode();
                            child.Name = d.id.ToString();
                            child.Tag = d.code;
                            child.Text = "[" + d.code + "]" + d.name;
                            child.ImageIndex = 3;
                            node.Nodes.Add(child);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 初始化表格列
        /// </summary>
        private void initDgvColumns()
        {
            this.uDataGridView1.AutoGenerateColumns = false;
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Code", "代号", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Id", "物料Id", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "StockId", "库存Id", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "CnName", "名称", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Specs", "规格", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "CategoryName", "分类", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "StockDepotName", "仓库", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "CurrentStockNum", "库存", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "BatchNo", "批号", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "expire", "有效期", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "DepartmentCode", "生产部门代号", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "DepartmentName", "生产部门", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Brand", "品牌", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewCheckBoxColumn(), "Unusable", "停用", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Unit", "单位", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "DepotArea", "库位", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "PrjtCode", "工程号", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "PrjtId", "工程Id", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "ProviderName", "主供应商", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "ProviderCode", "主供应商号", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Source", "来源", true, true, null);
        }

        /// <summary>
        /// Dgv字段绑定过滤器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void initDgvFilter(object sender, ColumnFilterEventArgs e)
        {
            switch (e.Column.DataPropertyName)
            {
                case "CategoryName":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "CurrentStockNum":
                    {
                        e.ColumnFilter = new DgvNumRangeColumnFilter();
                        break;
                    }
                case "BatchNo":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "StockDepotName":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "DepartmentName":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "Brand":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "Unusable":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "expire":
                    {
                        e.ColumnFilter = new DgvDateColumnFilter();
                        break;
                    }
                case "Unit":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "Source":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "ProviderName":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                default:
                    {
                        e.ColumnFilter = new DgvTextBoxColumnFilter();
                        break;
                    }
            }
            e.Handled = true;
        }

        private void bindGV(int? type, int? depotCategory, int? depot)
        {
            if (this._DgvFm.DataGridView != null)
                this._DgvFm.ActivateAllFilters(false);
            this.DataAry = this.BaseDataProxy.FindMaterials(this.StockNullable, type, depotCategory, depot, this.textBox1.Text.Trim(), this.textBox2.Text.Trim(), this.textBox3.Text.Trim(),null,IsPurchase,null);
            if (DataAry != null)
            {
                DataTable dt = DataAry.ToDataTable();
                this.uDataGridView1.DataSource = dt;
                if (dt.Rows.Count > 0)
                    this._DgvFm.DataGridView = this.uDataGridView1;
            }
        }

        private void uTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Name != string.Empty)
            {
                bindGV(Convert.ToInt32(e.Node.Name), null, null);
            }
            else
                bindGV(null, null, null);
        }

        private void uTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.uTabControl1.SelectedIndex == 1)
            {
                this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.仓库分类;
                bindTree(this.uTreeView2);
            }
            else
            {
                this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.物料分类;
                bindTree(this.uTreeView1);
            }
        }

        private void uTreeView2_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Name != string.Empty)
            {
                if (e.Node.ImageIndex == 3)
                    bindGV(null, null, Convert.ToInt32(e.Node.Name));
                else if (e.Node.ImageIndex == 2)
                    bindGV(null, Convert.ToInt32(e.Node.Name), null);
                else
                    bindGV(null, null, null);
            }
            else
                bindGV(null, null, null);
        }

        private void uDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!this.MutiSelect)
            {
                singleSelect();
                this.Close();
            }
        }

        /// <summary>
        /// 发送结果给调用窗体
        /// </summary>
        private void raiseEvent(object sender, EventArgs e)
        {
            QMaterial[] items = getSelectedItems();
            if (items != null)
            {
                CommonEventArg<QMaterial[]> arg = new CommonEventArg<QMaterial[]>(items, Common.OperateType.Add);
                GRWL.BZSC.Common.EventCommon.OnFindMaterialUdDGVEvnt(sender, arg);
            }
        }

        private QMaterial[] getSelectedItems()
        {
            try
            {
                if (this.uDataGridView1.SelectedRows != null && this.DataAry != null)
                {
                    List<QMaterial> list = new List<QMaterial>() { };
                    for (int i = 0; i < this.uDataGridView1.SelectedRows.Count; i++)
                    {
                        QMaterial qm = null;
                        if (this.StockNullable)
                            qm = this.DataAry.First(p => p.Id == Convert.ToInt32(this.uDataGridView1.SelectedRows[i].Cells[1].Value));

                        else
                            qm = this.DataAry.First(p => p.Id == Convert.ToInt32(this.uDataGridView1.SelectedRows[i].Cells[1].Value) && p.StockId == Convert.ToInt32(this.uDataGridView1.SelectedRows[i].Cells[2].Value));

                        if (qm != null && !list.Contains(qm))
                            list.Add(qm);

                    }
                    return list.ToArray();
                }
            }
            catch { }
            return null;
        }

        private void singleSelect()
        {
            if (this.uDataGridView1.SelectedRows != null && this.DataAry != null)
            {
                if (this.StockNullable)
                    this.SelectorItem = this.DataAry.First(p => p.Id == Convert.ToInt32(this.uDataGridView1.SelectedRows[0].Cells[1].Value));
                else
                    this.SelectorItem = this.DataAry.First(p => p.Id == Convert.ToInt32(this.uDataGridView1.SelectedRows[0].Cells[1].Value) && p.StockId == Convert.ToInt32(this.uDataGridView1.SelectedRows[0].Cells[2].Value));
                this.DialogResult = DialogResult.OK;
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (this.MutiSelect)
                raiseEvent(sender, e);
            else
                singleSelect();
            this.Close();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            bindGV(null, null, null);
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            raiseEvent(sender, e);
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            if (this.uDataGridView1.Rows != null)
            {
                for (int i = 0; i < this.uDataGridView1.Rows.Count; i++)
                    this.uDataGridView1.Rows[i].Selected = true;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            if (this.uDataGridView1.Rows != null)
            {
                for (int i = 0; i < this.uDataGridView1.Rows.Count; i++)
                    this.uDataGridView1.Rows[i].Selected = false;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void uDataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.uDataGridView1);
        }

        private void uDataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.uDataGridView1);
        }
    }
}
